package br.com.eSink.tests;

import br.com.eSink.connection.Sync;
import br.com.esink.tests.Logging;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;

public class TestConnection extends javax.swing.JFrame {

    private static ServerSocket srv;  

    /*
     * ENVIAR ARQUIVOS:
     * Transmissao.sendFiles(SOCKET, FILE);
     * 
     * RECEBER ARQUIVOS:
     * Transmissao.requestFiles(SOCKET, CAMINHO);
     * 
     * RECEBER IP:
     * STRING = IPAddress.getIPAddress(true);
     * 
     * TENTAR CRIAR CONEXAO A PARTIR DO CLIENTE:
     * SOCKET = IPAddress.checkHosts(ip);
     * 
     */
    public TestConnection() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnserver = new javax.swing.JToggleButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtLog = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btnserver.setLabel("Iniciar Server");
        btnserver.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnserverActionPerformed(evt);
            }
        });

        txtLog.setEditable(false);
        txtLog.setColumns(20);
        txtLog.setRows(5);
        jScrollPane2.setViewportView(txtLog);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 465, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnserver)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnserver)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnserverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnserverActionPerformed
        
        try {
            srv = new ServerSocket(6789);      
            txtLog.append("Server Criado\n");
            Logging.write("Server Criado\n", false);  
        } catch (IOException ex) {
            txtLog.append("\nServer não foi criado:" + ex.getMessage());
            System.out.println("Server não foi Criado:" + ex.getMessage());
        }

        //ESPERA PARA CONECTAR A UM CLIENTE
        Thread recebe = new Thread("Connect") {
            @Override
            public void run() {
                boolean connected = false;
                while (!connected) {
                    
                    try {
                        txtLog.append("Cliente Criado");
                        Logging.write("Cliente Criado\n", true);  
                        Sync cli = new Sync(srv.accept());
                        cli.start();              
                        connected = true;
                    } catch (IOException ex) {
                        txtLog.append("\nConexão com cliente não estabelecida:" + ex.getMessage());
                        System.out.println("Conexão com cliente não estabelecida:" + ex.getMessage());
                    }
                }
            }
        };
        recebe.start();
        try {
            recebe.join();
        } catch (InterruptedException ex) {
            txtLog.append(ex.getMessage());
        }

    }//GEN-LAST:event_btnserverActionPerformed

    public static void main(String args[]) {

        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TestConnection.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TestConnection.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TestConnection.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TestConnection.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>


        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TestConnection().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JToggleButton btnserver;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea txtLog;
    // End of variables declaration//GEN-END:variables
}
